import { Component, ViewChild } from '@angular/core';
import { LoadingController } from '@ionic/angular';
import { NgEventBus } from 'ng-event-bus';
import { Constant } from 'src/app/model/constants';
import { SentenceService } from 'src/app/service';
import { ToastService } from 'src/app/service/toast.service';

@Component({
  selector: 'app-adding',
  templateUrl: 'collection.page.html',
  styleUrls: ['collection.page.scss'],
})
export class CollectionPage {
  @ViewChild('sentence')
  public sentence: any;

  public spitSentence = true;
  public exceedMax = false;
  public lineNum: number;
  constructor(
    private toastService: ToastService,
    private sentenceService: SentenceService,
    private eventBus: NgEventBus,
    private loadingCtrl: LoadingController
  ) {}

  public async addSentence() {
    const loading = await this.loadingCtrl.create({
      message: '数据处理...',
    });
    await loading.present();
    try {
      if (this.spitSentence) {
        const lines = this.sentence.value.trim().split(/\r?\n/);
        this.lineNum = lines.length;

        let i = 0;
        for (const line of lines) {
          if (!line) {
            continue;
          }
          i++;
          await this.sleep(1000);
          await this.sentenceService.collectNewSentence(line).toPromise();
          this.sentence.value = this.sentence.value.trim().replace(line, '');
        }
        this.sentence.value = '';
        this.toastService.showInfo(`${i}个句子添加成功`);
      } else {
        await this.sentenceService
          .collectNewSentence(this.sentence.value)
          .toPromise();
        this.sentence.value = '';
        this.toastService.showInfo('1个句子添加成功');
      }
      await loading.dismiss();
      this.eventBus.cast(Constant.Event_Update_Queue, {
        direction: Constant.Direction_Keep,
      });
    } catch (err) {
      this.toastService.showError(err.statusText);
      await loading.dismiss();
    }
  }
  public ionChange(event) {
    this.spitSentence = event.detail.checked;
    this.change();
  }
  public change() {
    if (this.spitSentence) {
      const lines = this.sentence.value.trim().split(/\r?\n/);
      this.lineNum = lines.length;
      if (this.lineNum > 520) {
        this.exceedMax = true;
      } else {
        this.exceedMax = false;
      }

      for (const line of lines) {
        if (!line) {
          continue;
        }
        if (line.length > 1200) {
          this.exceedMax = true;
        }
      }
    } else {
      const lines = this.sentence.value.trim().split();
      this.lineNum = lines.length;
      if (this.sentence.value.trim().length > 1200) {
        this.exceedMax = true;
      } else {
        this.exceedMax = false;
      }
    }
  }

  private sleep(time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }
}
